import React, { Component } from "react";
import { NavBar, Icon, SearchBar } from "antd-mobile";
import { withRouter } from "react-router-dom";
import { getProdcutList } from "../data/api";
import "./SearchCenter.scss";
class SearchCenter extends Component {
  timeId = null;
  // 防抖
  debounce = (fn, timeout) => {
    if (this.timeId) {
      clearTimeout(this.timeId);
      this.timeId = null;
    }
    this.timeId = setTimeout(fn, timeout);
  };
  state = {
    productList: [],
    value: "",//输入框的值
    searchHistory: []//搜索的历史记录
  };
  // 跳转产品详情页面
  handleClick = (goods_id) => {
    this.props.history.push("goodDetail?goods_id=" + goods_id);
  };
  componentDidMount() {
    window.addEventListener('handleChange', e => e.preventDefault())
    // this.getHistoryItems();
    // this.clearHistory();
    //5.获取localstorage的值，保存到state中
    // data.reverse()
    this.setState({
      searchHistory: JSON.parse(localStorage.getItem('data'))
    })
  }
  //搜索框内容改变事件
  handleChange = async (value) => {
    this.debounce(async () => {
      let res = await getProdcutList({ query: value });
      this.setState(() => {
        return {
          productList: res.message || [], // res.message === null  null||[]
          value: value
        };
      });

    }, 500)
  };
  handleSearch = (params) => {
    // var locat=JSON.parse(localStorage.getItem('data'))
    //1.深拷贝原始数据
    let arr1 = JSON.parse(JSON.stringify(this.state.searchHistory)) || []
    let value = this.state.value
    
    //2.把数据追加到数组中
    if(arr1.length<20){
      arr1.unshift(value)
      console.log(arr1);
    }

    //3.将数组保存到state中
    this.setState({
      searchHistory: arr1
    })

    //4.将数组中的值保存到localstoryge中
    
    localStorage.setItem('data', JSON.stringify(arr1));
    

  }
  handleDelete = (params) => {
    localStorage.clear();
    this.setState({
      searchHistory: ""
    })
  }
  render() {
    return (
      <div className="pxxSearChCenter">
        <NavBar
          onLeftClick={() => this.props.history.go(-1)}
          icon={<Icon type="left" />}
        >
          <SearchBar
            v-model={this.state.value}
            placeholder="iphone12Pro"
            onSubmit={value => console.log(value, 'onSubmit')}
            showCancelButton
            cancelText="搜索"
            onCancel={this.handleSearch}
            onChange={this.handleChange}
          />

        </NavBar>
        <div className="searchSenterList">
          {this.state.productList.map((v) => {
            return (
              <div
                className="productListItem"
                key={v.goods_id}
                onClick={this.handleClick.bind(this, v.goods_id)}
              >
                {v.goods_name}
              </div>
            );
          })}
        </div>
        <div className={this.state.value === '' ? "searchSenterContent" : 'hidden'}>
          <div className="searchCenterTop">
            <div className="leastSearch">
              <div className="searchType">最近搜索</div>
              <div className="iconfont icon-shanchu deleteSearch" onClick={this.handleDelete}></div>
            </div>
            {
              this.state.searchHistory && this.state.searchHistory.map((v, index) => {
                return <div className="searchTitle" key={index}>
                  {v}
                </div>
              })
            }
          </div>
          <div className="SearchCenterMiddle">
            <div className="searchType">更多搜索方式</div>
            <div className="searchStore">
              <div className="searchButtonLeft">
                <div>搜索店铺</div>
                <div> &gt; </div>
              </div>
              <div className="searchButtonRight">
                <div>图片搜索</div>
                <div> &gt; </div>
              </div>
            </div>
          </div>
          <div className="searchCenterButtom">
            <div className="searchType">搜索发现</div>
            <div className="searchInfo">
              <div className="searchTitle">魔芋爽</div>
              <div className="searchTitle">雪地靴女</div>
              <div className="searchTitle">运动鞋</div>
              <div className="searchTitle">苹果6S</div>
              <div className="searchTitle">漱口水</div>
              <div className="searchTitle">汽车神器</div>
              <div className="searchTitle">洗衣液</div>
              <div className="searchTitle">水杯保温</div>
            </div>
          </div>
        </div>

      </div>
    );
  }
}

export default withRouter(SearchCenter);